<template>
    <TodoHeader @add-todo="handleAddTodo" />
    <TodoList>
      <draggable v-model="todos" item-key="id">
        <template #item="{ element }">
          <TodoItem
            v-bind="element"
            :class="{ 'rotate-enter': element.isNew }"
            @toggle="handleToggle"
            @edit="handleEdit"
            @delete="handleDelete"
          ></TodoItem>
        </template>
      </draggable>
    </TodoList>
    <TodoFooter
      :todos="todos"
      @toggle-all="handleToggleAll"
      @clear-done="handleClearDone"
      @clear-all="handleClearAll"
    />
  </template>
  
  <script setup>
  import { ref, onMounted, watch } from 'vue'
  import draggable from 'vuedraggable'
  
  import TodoHeader from './components/TodoHeader.vue'
  import TodoList from './components/TodoList.vue'
  import TodoFooter from './components/TodoFooter.vue'
  import TodoItem from './components/TodoItem.vue'
  
  const todos = ref([])
  
  const handleAddTodo = (todo) => {
    // 生成随机颜色
    const colors = [
      '#FFD6E7', // 浅粉色
      '#FFEFB5', // 浅黄色
      '#CCE5FF', // 浅蓝色
      '#FFCCCC', // 浅红色
      '#E0FFCC', // 浅绿色
      '#D9E5FF', // 淡蓝色
      '#F0E6FF', // 淡紫色
      '#F2E6D9', // 米黄色
      '#E6FFF2', // 淡青色
      '#F0F0F0'  // 浅灰色
    ];
    const randomColor = colors[Math.floor(Math.random() * colors.length)];
    
    todo.isNew = true;
    todo.backgroundColor = randomColor; // 添加背景颜色属性
    todos.value.push(todo);

    // 延迟移除 isNew 标志，确保动画完成
    setTimeout(() => {
      const addedTodo = todos.value.find((item) => item.id === todo.id);
      if (addedTodo) {
        delete addedTodo.isNew;
      }
    }, 2000);
  }
  
  const handleToggle = (id, value) => {
    // 根据id查找对应todo，修改done属性
    const todo = todos.value.find((item) => item.id === id)
    todo.done = value
  }
  
  const handleEdit = (id, value) => {
    const todo = todos.value.find((item) => item.id === id)
    todo.content = value
  }
  const handleDelete = (id) => {
    const index = todos.value.findIndex((item) => item.id === id)
    todos.value.splice(index, 1)
  }
  
  const handleToggleAll = (value) => {
    todos.value.forEach((todo) => {
      todo.done = value
    })
  }
  const handleClearDone = () => {
    todos.value = todos.value.filter((todo) => !todo.done)
  }
  const handleClearAll = () => {
    todos.value = []
  }
  watch(
    todos,
    () => {
      localStorage.setItem('todos', JSON.stringify(todos.value))
    },
    { deep: true }
  )
  onMounted(() => {
    todos.value = JSON.parse(localStorage.getItem('todos') || '[]')
  })
  </script>
  
  <style>
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  /* 定义旋转动画 */
@keyframes rotateIn {
  from {
    transform: rotate(180deg);
    opacity: 0;
  }
  to {
    transform: rotate(0deg);
    opacity: 1;
  }
}

/* 应用动画到新添加的 TodoItem */
.rotate-enter {
  animation: rotateIn 0.5s ease-in-out;
}
  </style>